var url = 'https://webapi.amap.com/maps?v=1.4.15&key=da0248ce65c46d26fed54c170ef3bfca&callback=onApiLoaded';
var jsapi = document.createElement('script');
jsapi.charset = 'utf-8';
jsapi.src = url;
document.head.appendChild(jsapi);
let centers = [
    {
        lng: 103.856602, lat: 30.688472, title: '中融集团温江分公司', icon: './img/xxlogo.png',
        address: '四川省成都市温江区柳城街道德坤·新天地德昆·新天地', phone: '15882397196'
    }
]
async function onApiLoaded() {
    var map = new AMap.Map("map", {
        zoom: 12,
        pitch: 50,
        showIndoorMap: false,
        zooms: [3, 20],
        expandZoomRange: true,
        showBuildingBlock: true,
        showLabel: true,
        mapStyle: "amap://styles/dark",
        center: [103.856602, 30.688472],
        features: ['road', 'buildings'],
        viewMode: '2D',
        layers: [
            new AMap.TileLayer({}),
        ]
    });
    map.plugin(['AMap.ToolBar', 'AMap.Scale', 'AMap.Autocomplete', 'AMap.PlaceSearch',
        'AMap.Driving', 'AMap.Weather', 'AMap.Geocoder', 'AMap.AdvancedInfoWindow', 'Map3D'], function () {
            var geocoder = new AMap.Geocoder({
                city: "全国", //城市设为北京，默认：“全国”
                radius: 100 //范围，默认：500
            })
            //获取标记点
            function getMark(centers) {
                for (let i = 0; i < centers.length; i++) {
                    var icon = new AMap.Icon({
                        size: new AMap.Size(35, 35),
                        image: './img/baoanlogo.png',
                        imageSize: new AMap.Size(35, 35)
                        // imageOffset: new AMap.Pixel(-25, -3)
                    });
                    let marker = new AMap.Marker({
                        size: new AMap.Size(10, 10),
                        position: new AMap.LngLat(centers[i].lng, centers[i].lat),
                        icon: icon,
                        title: centers[i].title
                    });
                    map.add(marker)
                }
            }
            getMark(centers);

            //弹起信息框
            async function openInfo(obj) {
                var info = [];
                info.push("<div><div><img style=\"float:left;\" src=\" https://webapi.amap.com/images/autonavi.png \"/></div> ");
                info.push(`<div style="padding:0px 0px 0px 4px;"><b>${obj.title}</b>`);
                info.push(`电话 : ${obj.phone}`);
                info.push(`地址 :${obj.address}</div></div>`);
                // info.push(`<div>
                // <button>查看此处监控</button>
                // </div>`);
                infoWindow = new AMap.InfoWindow({
                    content: info.join("<br/>")  //使用默认信息窗体框样式，显示信息内容
                });
                infoWindow.open(map, map.getCenter());
            }
            //根据经纬度获取地址
            async function getAddress(obj) {
                return new Promise(
                    (res, rej) => {
                        let lnglat = `${obj.lng},${obj.lat}`
                        geocoder.getAddress(lnglat, function (status, result) {
                            if (status === 'complete' && result.regeocode) {
                                getWeather(result.regeocode.addressComponent.adcode)
                                res(result)
                            } else {
                                rej(status)
                            }
                        })
                    }
                )
            }
            // 根据地理位置转为经纬度
            document.querySelector("#pickbtn").onclick = function () {
                axios.post(`${globalData.http}/list/getCustom`, {
                    page: 1,
                    limit: 200,
                    para: { where: { BMLX: "03", BMID: { $in: window.pickBranch }, SSGS: "001000000000000000000000000000" } }

                }).then(
                    res => {
                        geoCode(res.data.data)
                    }
                )

            }
            var markers = [];

            async function geoCode(arr) {
                map.remove(markers);
                markers = [];
                var addresses = arr.map(function (item) {
                    geocoder.getLocation(item.DZ, function (status, result) {

                        if (status === 'complete' && result.geocodes.length) {
                            for (var i = 0; i < result.geocodes.length; i += 1) {
                                let myicon = {}
                                switch (item.BMID) {
                                    //xiaoyuan
                                    case '001003002001000000000000000000': {

                                        myicon = new AMap.Icon({
                                            size: new AMap.Size(35, 35),    // 图标尺寸
                                            image: './img/xxlogo.png',  // Icon的图像
                                            imageSize: new AMap.Size(35, 35)   // 根据所设置的大小拉伸或压缩图片
                                        });
                                        addmarker(myicon)
                                        break;

                                    }
                                    //yinhang
                                    case '001003002002000000000000000000': {
                                        myicon = new AMap.Icon({
                                            size: new AMap.Size(35, 35),    // 图标尺寸
                                            image: './img/yhlogo.png',  // Icon的图像
                                            imageSize: new AMap.Size(35, 35)   // 根据所设置的大小拉伸或压缩图片
                                        });
                                        addmarker(myicon)
                                        break;
                                    }
                                    //yuelecahngsuo
                                    case '001003002003000000000000000000': {
                                        myicon = new AMap.Icon({
                                            size: new AMap.Size(35, 35),    // 图标尺寸
                                            image: './img/yllogo.png',  // Icon的图像
                                            imageSize: new AMap.Size(35, 35)   // 根据所设置的大小拉伸或压缩图片
                                        });
                                        addmarker(myicon)
                                        break;
                                    }
                                    //gongan
                                    case '001003001001000000000000000000': {
                                        myicon = new AMap.Icon({
                                            size: new AMap.Size(35, 35),    // 图标尺寸
                                            image: './img/jclogo.png',  // Icon的图像
                                            imageSize: new AMap.Size(35, 35)   // 根据所设置的大小拉伸或压缩图片
                                        });
                                        addmarker(myicon)
                                        break;
                                    }
                                    //wangge
                                    case '001003001002000000000000000000': {
                                        myicon = new AMap.Icon({
                                            size: new AMap.Size(35, 35),    // 图标尺寸
                                            image: './img/wglogo.png',  // Icon的图像
                                            imageSize: new AMap.Size(35, 35)   // 根据所设置的大小拉伸或压缩图片
                                        });
                                        addmarker(myicon)
                                        break;
                                    }
                                    default: {
                                        myicon = new AMap.Icon({
                                            size: new AMap.Size(35, 35),    // 图标尺寸
                                            image: './img/qylogo.png',  // Icon的图像
                                            imageSize: new AMap.Size(35, 35)   // 根据所设置的大小拉伸或压缩图片
                                        });
                                        addmarker(myicon)
                                        break;
                                    }
                                }
                                function addmarker(myicon) {
                                    var marker = new AMap.Marker({
                                        position: result.geocodes[i].location,
                                        title: item.MC,
                                        icon: myicon,
                                        extData: { ID: item.ID, MC: item.MC }
                                    });
                                    marker.on('click', function (res) {
                                       
                                        let obj = { lng: res.lnglat.lng, lat: res.lnglat.lat }
                                        getAddress(obj).then(
                                            re => {
                                                getWeather(re.regeocode.addressComponent.adcode,res)
                                            }
                                        )
                                        console.log(res)
                                        $('#jifang').text(`${res.target.w.extData.MC}`)
                                        getRelatePeople(res.target.w.extData.ID)
                                    });
                                    markers.push(marker);
                                }
                            }
                            map.add(markers);

                            map.setFitView(markers);
                        }
                    });
                    // return item.DZ
                });

            }

            // 根据起终点经纬度规划驾车导航路线
            var driving = new AMap.Driving({
                map: map,
                panel: "panel"
            });

            // driving.search(new AMap.LngLat(104.076964, 30.628724), new AMap.LngLat(103.856602, 30.688472), function (status, result) {
            //     if (status === 'complete') {
            //     } else {
            //     }
            // });


            //天气预报
            async function getWeather(city,mark) {
                var weather = new AMap.Weather();
                //查询实时天气信息, 查询的城市到行政级别的城市，如朝阳区、杭州市
                weather.getLive(city, function (err, data) {
                    let title = data.city
                   if(mark) title = mark.target.B.title
                    if (!err) {
                        var str = `
                   <div class="cen">实时天气</div>
                   <div class="col">
                      <div>地点： ${title}</div>
                      <div>天气： ${data.weather}</div>
                      <div>温度： ${data.temperature}℃</div>
                      <div>风向： ${data.windDirection}</div>
                      <div>风力： ${data.windPower}级</div>
                      <div>空气湿度： ${data.humidity}</div>
                      <div class='publishTime'>发布时间： ${data.reportTime}</div>
                   </div>
                `;
                    }
                    $("#cage_cl1").html(str)

                })
                weather.getForecast(city, function (err, data) {
                    if (err) { return; }
                    var str = '';
                    for (var i = 0, dayWeather; i < data.forecasts.length; i++) {
                        dayWeather = data.forecasts[i];
                        str += ('<div>' + dayWeather.date + ' <span class="weather">' + dayWeather.dayWeather + '</span> '
                            + dayWeather.nightTemp + '~' + dayWeather.dayTemp + '℃' + '</div>');
                    }
                    $("#cage_cl2").html(`<div class="cen">预报天气</div><div class="col">${str}</div>`)
                });


            }
            getWeather('温江区');
            // 事件监听
            document.querySelector("#zoomOut").onclick = function () {
                map.setZoom(map.getZoom() + 1)
            }
            document.querySelector("#zoomIn").onclick = function () {
                map.setZoom(map.getZoom() - 1)
            }
            document.querySelector("#Search").onclick = function () {
                $('#searchinfo').toggle().css({ "top": "6%" })
                $(".display_box").hide()
            }
            document.querySelector("#fresh_tool").onclick = function () {
                $(".display_type_box").hide()
                $(".city_chose_box").hide()
                $("#searchinfo").hide()
                $(".display_theme_box").hide()
                $(".display_feature_box").hide()
                map.setCenter([103.856602, 30.688472]);
                if(window.addr){
                    map.remove(window.addr)
                }
                map.remove(markers);
            }

            document.querySelector("#selectType").onclick = function () {
                // $(".display_type_box").hide()
                // $(".city_chose_box").hide()
                $(".display_theme_box").hide()
                $("#searchinfo").hide()
            }
            //特征显示
            document.querySelector("#features").onclick = function () {
                $(".display_type_box").hide()
                $(".city_chose_box").hide()
                $("#searchinfo").hide()
                $(".display_theme_box").hide()
                $(".display_feature_box").toggle()
            }
            document.querySelector("#featureBtn").onclick = function () {

                $(".display_feature_box").toggle()
            }

            //设置地图显示要素
            function setMapFeatures() {
                var features = [];
                var inputs = document.querySelectorAll("#map-features input");
                inputs.forEach(function (input) {
                    if (input.checked) {
                        features.push(input.value);
                    }
                });
                map.setFeatures(features);
            }

            // 主题样式
            //绑定radio点击事件
            document.querySelector("#themes").onclick = function () {
                $(".display_type_box").hide()
                $(".city_chose_box").hide()
                $("#searchinfo").hide()
                $(".display_feature_box").hide()
                $(".display_theme_box").toggle()
            }
            document.querySelector("#themeBtn").onclick = function () {

                $(".display_theme_box").toggle()
            }
            var radios = document.querySelectorAll("#map-styles input");
            radios.forEach(function (ratio) {
                ratio.onclick = setMapStyle;
            });

            function setMapStyle() {
                var styleName = "amap://styles/" + this.value;
                map.setMapStyle(styleName);
            }
            //绑定checkbox点击事件
            var inputs = document.querySelectorAll("#map-features input");
            inputs.forEach(function (checkbox) {
                checkbox.onclick = setMapFeatures;
            });

            // 搜索
            document.querySelector("#beginSearch").onclick = function () {
                map.setZoom(map.getZoom() + 1)
                var keywords = $('#tipinput').val();
                var autoOptions = {
                    city: '全国'
                }
                var placeSearch = new AMap.PlaceSearch(autoOptions);
                placeSearch.search(keywords, function (status, result) {
                    // 搜索成功时，result即是对应的匹配数据
                    if (result.poiList.pois[0]) {
                        let pos = result.poiList.pois[0].location
                        map.setZoomAndCenter(16, [pos.lng, pos.lat])
                        window.addr = new AMap.Marker({
                            position: new AMap.LngLat(pos.lng, pos.lat),
                            title: result.poiList.pois[0].name
                        });
                        map.add(addr);
                    } else {
                        alert('地址不存在')
                    }
                })
            }
            var auto = new AMap.Autocomplete({
                input: "tipinput"
            });
            //根据地址获取相关安保人员

            async function getRelatePeople(ID) {
                getBaoAn(ID)
                // axios.post(`${globalData.http}/list/getRelatePeople`, {
                //     page:1,
                //     limit:200,
                //     para: {where:{SSDW:ID}}
                // }).then(
                //     res => {
                //         window.guard = res.data
                //         getBaoAn(res.data)
                //     }
                // )
            }

            // 卫星图层
            let haveSate = false
            var satellite = new AMap.TileLayer.Satellite({
                map: null,
            });
            document.querySelector("#satellite").onclick = function () {
                if (haveSate == false) {
                    satellite.setMap(map);
                    haveSate = true
                } else {
                    satellite.setMap(null);
                    haveSate = false
                }

            }
            document.querySelector("#getBeforeVideo").onclick = function () {
                
                if(window.playNum > 0){
                    window.playNum--;
                    getListVideo().then(
                        arr=>{
                            $("#detail").empty();
                            getVideo(arr[window.playNum], 'v2','detail');
                        }
                    );
                }
                else{
                    window.playNum = 32
                    getListVideo().then(
                        arr=>{
                            $("#detail").empty();
                            getVideo(arr[window.playNum], 'v2','detail');
                        }
                    );
                    // alert('已经是第一个了')
                }
            }
            document.querySelector("#getNextVideo").onclick = function () {
                if(window.playNum < 33){
                    window.playNum++;
                    getListVideo().then(
                        arr=>{
                            $("#detail").empty();
                            getVideo(arr[window.playNum], 'v2','detail');
                        }
                    );
                }
                else{
                    window.playNum=0
                    getListVideo().then(
                        arr=>{
                            $("#detail").empty();
                            getVideo(arr[window.playNum], 'v2','detail');
                        }
                    );
                    // alert('已经是最后一个了')
                }
            
            }

        }
    )
}
// 放大缩小
var isAllScreen = false
function zoomFull() {
    if (isAllScreen) {
        $('#changeMap').css({
            "z-index": "1", "position": "relative", "height": "95%", "width": "100%",
            "top": "0", "left": "0"
        });
        isAllScreen = false
    }
    else {
        $('#changeMap').css({
            "z-index": "4", "position": "fixed", "height": "100vh", "width": "100vw",
            "top": "0", "left": "0"
        });
        isAllScreen = true
    }
}

